Page({
  data: {
    // 时间和状态信息
    currentTime: "10:23",
    showToast: false,
    toastText: "",
    showGuide: true,
    isRecognizing: false,
    isLoading: false,
    cameraMode: 'back', // back, front
    brightness: 1.0,
    contrast: 1.0,
    
    // 内容数据
    currentPoetryIndex: 0,
    poetryData: [
      {
        lines: ["明月松间照", "清泉石上流"],
        title: "山居秋暝",
        author: "王维",
        dynasty: "唐代",
        meaning: "皎皎明月从松隙间洒下清光，清清泉水在山石上淙淙淌流。"
      },
      {
        lines: ["白日依山尽", "黄河入海流"],
        title: "登鹳雀楼",
        author: "王之涣",
        dynasty: "唐代",
        meaning: "夕阳依傍着山峦慢慢沉落，滔滔黄河朝着大海汹涌奔流。"
      },
      {
        lines: ["大漠孤烟直", "长河落日圆"],
        title: "使至塞上",
        author: "王维",
        dynasty: "唐代",
        meaning: "浩瀚沙漠中孤烟直上，无尽黄河上落日浑圆。"
      },
      {
        lines: ["两个黄鹂鸣翠柳", "一行白鹭上青天"],
        title: "绝句",
        author: "杜甫",
        dynasty: "唐代",
        meaning: "两只黄鹂在翠绿的柳树间婉转地歌唱，一队整齐的白鹭直冲向蔚蓝的天空。"
      },
      {
        lines: ["接天莲叶无穷碧", "映日荷花别样红"],
        title: "晓出净慈寺送林子方",
        author: "杨万里",
        dynasty: "宋代",
        meaning: "那密密层层的荷叶铺展开去，与蓝天相连接，一片无边无际的青翠碧绿；那亭亭玉立的荷花绽蕾盛开，在阳光辉映下，显得格外的鲜艳娇红。"
      },
      {
        lines: ["床前明月光", "疑是地上霜"],
        title: "静夜思",
        author: "李白",
        dynasty: "唐代",
        meaning: "明亮的月光洒在床前的窗户纸上，好像地上泛起了一层霜。"
      },
      {
        lines: ["春眠不觉晓", "处处闻啼鸟"],
        title: "春晓",
        author: "孟浩然",
        dynasty: "唐代",
        meaning: "春日里贪睡不知不觉天已破晓，搅乱我酣眠的是那啁啾的小鸟。"
      },
      {
        lines: ["飞流直下三千尺", "疑是银河落九天"],
        title: "望庐山瀑布",
        author: "李白",
        dynasty: "唐代",
        meaning: "高崖上飞腾直落的瀑布好像有几千尺，让人恍惚以为银河从天上泻落到人间。"
      }
    ],
    
    // 动画相关
    floatAnimation: {},
    floatAnimation2: {},
    markerAnimation: {},
    
    // 识别历史
    recognitionHistory: []
  },

  onLoad() {
    // 更新当前时间
    this.updateTime();
    setInterval(() => this.updateTime(), 60000);
    
    // 初始化动画
    this.initAnimations();
    
    // 尝试获取用户授权
    this.requestCameraPermission();
    
    // 启动模拟AR识别
    this.startSimulatedRecognition();
  },

  onShow() {
    // 页面显示时恢复动画
    if (this.animationTimer) {
      clearTimeout(this.animationTimer);
    }
    this.loopAnimations();
  },

  onHide() {
    // 页面隐藏时停止动画
    if (this.animationTimer) {
      clearTimeout(this.animationTimer);
    }
  },

  onUnload() {
    // 页面卸载时清理资源
    if (this.recognitionTimer) {
      clearInterval(this.recognitionTimer);
    }
    if (this.animationTimer) {
      clearTimeout(this.animationTimer);
    }
  },

  // 更新当前时间
  updateTime() {
    const date = new Date();
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    this.setData({
      currentTime: `${hours}:${minutes}`
    });
  },

  // 初始化动画
  initAnimations() {
    // 第一个诗句动画
    const animation1 = wx.createAnimation({
      duration: 3000,
      timingFunction: 'ease-in-out',
    });
    this.animation1 = animation1;
    
    // 第二个诗句动画
    const animation2 = wx.createAnimation({
      duration: 3000,
      timingFunction: 'ease-in-out',
    });
    this.animation2 = animation2;
    
    // 标记动画
    const markerAnimation = wx.createAnimation({
      duration: 2000,
      timingFunction: 'ease-in-out',
    });
    this.markerAnimation = markerAnimation;
    
    this.loopAnimations();
    this.loopMarkerAnimation();
  },

  // 循环诗句动画
  loopAnimations() {
    this.animation1.translateY(-20).step();
    this.animation1.translateY(0).step({duration: 3000});
    
    this.animation2.translateY(-20).step({delay: 1500});
    this.animation2.translateY(0).step({duration: 3000});
    
    this.setData({
      floatAnimation: this.animation1.export(),
      floatAnimation2: this.animation2.export()
    });
    
    this.animationTimer = setTimeout(() => this.loopAnimations(), 6000);
  },

  // 循环标记动画
  loopMarkerAnimation() {
    this.markerAnimation.scale(1.2).step();
    this.markerAnimation.scale(1).step({duration: 2000});
    
    this.setData({
      markerAnimation: this.markerAnimation.export()
    });
    
    setTimeout(() => this.loopMarkerAnimation(), 4000);
  },

  // 请求相机权限
  requestCameraPermission() {
    wx.getSetting({
      success: (res) => {
        if (!res.authSetting['scope.camera']) {
          wx.authorize({
            scope: 'scope.camera',
            success: () => {
              this.showToast('相机权限已获取');
            },
            fail: () => {
              this.showToast('请在设置中允许相机权限');
              wx.openSetting();
            }
          });
        }
      }
    });
  },

  // 模拟AR识别过程
  startSimulatedRecognition() {
    this.recognitionTimer = setInterval(() => {
      if (Math.random() > 0.7) { // 30%的概率触发识别
        this.setData({ isRecognizing: true });
        setTimeout(() => {
          this.setData({ isRecognizing: false });
          this.changeContent();
          this.addToRecognitionHistory(this.data.poetryData[this.data.currentPoetryIndex]);
        }, 1500);
      }
    }, 5000);
  },

  // 显示提示信息
  showToast(text) {
    this.setData({
      showToast: true,
      toastText: text
    });
    setTimeout(() => {
      this.setData({ showToast: false });
    }, 2000);
  },

  // 返回上一页
  navigateBack() {
    wx.navigateBack({
      delta: 1
    });
  },

  // 拍照功能
  takePhoto() {
    this.setData({ isLoading: true });
    // 模拟拍照过程
    setTimeout(() => {
      this.setData({ isLoading: false });
      this.showToast('照片已保存到相册');
      // 实际项目中应调用wx.chooseImage等API
    }, 800);
  },

  // 切换摄像头
  switchCamera() {
    const newMode = this.data.cameraMode === 'back' ? 'front' : 'back';
    this.setData({ cameraMode: newMode });
    this.showToast(`已切换到${newMode === 'back' ? '后置' : '前置'}摄像头`);
  },

  // 切换内容
  changeContent() {
    let newIndex = this.data.currentPoetryIndex + 1;
    if (newIndex >= this.data.poetryData.length) {
      newIndex = 0;
    }
    this.setData({
      currentPoetryIndex: newIndex
    });
  },

  // 调整亮度
  adjustBrightness(e) {
    const direction = e.currentTarget.dataset.direction;
    let brightness = this.data.brightness;
    if (direction === 'up' && brightness < 2.0) {
      brightness += 0.1;
    } else if (direction === 'down' && brightness > 0.1) {
      brightness -= 0.1;
    }
    this.setData({ brightness });
    this.showToast(`亮度: ${Math.round(brightness * 100)}%`);
  },

  // 查看诗词详情
  viewPoetryDetail() {
    const currentPoetry = this.data.poetryData[this.data.currentPoetryIndex];
    wx.navigateTo({
      url: '/pages/poetry-detail/poetry-detail?data=' + JSON.stringify(currentPoetry)
    });
  },

  // 添加到识别历史
  addToRecognitionHistory(poetry) {
    const history = this.data.recognitionHistory;
    const exists = history.some(item => item.title === poetry.title);
    if (!exists) {
      history.unshift({
        ...poetry,
        timestamp: new Date().toLocaleString()
      });
      // 限制历史记录数量
      if (history.length > 10) {
        history.pop();
      }
      this.setData({ recognitionHistory: history });
    }
  },

  // 分享当前内容
  shareContent() {
    const currentPoetry = this.data.poetryData[this.data.currentPoetryIndex];
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    this.showToast('分享选项已打开');
  },

  // 显示引导
  showGuide() {
    this.setData({ showGuide: true });
  },

  // 隐藏引导
  hideGuide() {
    this.setData({ showGuide: false });
    // 保存用户偏好
    wx.setStorageSync('arGuideShown', true);
  },

  // 长按识别标记触发更多操作
  longPressMarker() {
    wx.showActionSheet({
      itemList: ['查看诗词详情', '收藏诗词', '分享当前画面'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.viewPoetryDetail();
            break;
          case 1:
            this.saveToFavorites();
            break;
          case 2:
            this.shareContent();
            break;
        }
      }
    });
  },

  // 保存到收藏夹
  saveToFavorites() {
    const currentPoetry = this.data.poetryData[this.data.currentPoetryIndex];
    // 在实际项目中，这里应该调用API保存到用户收藏
    this.showToast('诗词已添加到收藏');
  }
});
